package kr.ac.mju.mdc.mjuapp.green;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import kr.ac.mju.mdc.mjuapp.R;
import kr.ac.mju.mdc.mjuapp.http.HttpManager;
import kr.ac.mju.mdc.mjuapp.network.NetworkManager;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author davidkim
 *
 */
public class GreencampusWriteActivity extends Activity implements Runnable {
	private final int RQ_PICTURE_SELECT = 1;

	private final int PROGRESS_DIALOG = 10;
	private final int PICTURE_SELECT_DIALOG = 11;

	private final int UPLOAD_SUCCESS = 20;
	private final int UPLOAD_FAIL = 21;

	/* 인텐트로 넘겨받을 상수값 */
	private final int WRITE_ARTS = 30; // 에너지낭비 신고하기(인문)
	private final int WRITE_SCIENCES = 31; // 에너지낭비 신고하기(자연)
	private final int WRITE_SELF = 32; // 본인조치 결과 신고하
	private final int WRITE_SUGGEST = 33; // 제안합니다

	private ArrayList<String> absoluteFileList;

	private String addImagePath = new String();
	private int imgWidth = 0; // defualt if fail to get width
	private int imgHeight = 0; // default if gail to get height

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int what = msg.what;
			switch (what) {
			case UPLOAD_SUCCESS:
				dismissDialog(PROGRESS_DIALOG);
				Toast.makeText(getApplicationContext(), "글 등록이 성공하였습니다.", Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(GreencampusWriteActivity.this, GreencampusListActivity.class);
				startActivity(intent);
				finish();
				break;
			case UPLOAD_FAIL:
				dismissDialog(PROGRESS_DIALOG);
				Toast.makeText(getApplicationContext(), "글 등록이 실패하였습니다.", Toast.LENGTH_SHORT).show();
				// error weak signal msg
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_network_error_weak_signal),
						Toast.LENGTH_SHORT).show();
				finish();
				break;
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.greencampus_write_layout);
		// create addFileList
		absoluteFileList = new ArrayList<String>();

		// complaint spinner
		Spinner complaint = (Spinner) findViewById(R.id.green_write_complaint_spinner);
		ArrayAdapter<CharSequence> complaintAdapter = ArrayAdapter.createFromResource(getApplicationContext(),
				R.array.green_write_complaint_arr, android.R.layout.simple_spinner_item);
		complaintAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		complaint.setAdapter(complaintAdapter);

		// 인텐트에서 상수값을 받아와서 어떤 신고인지 판단.
		Intent intent = getIntent();
		int which = intent.getIntExtra("write_which", 0);
		int select = which; // default
		if (which == WRITE_ARTS) {
			select = 0; // 1st
		} else if (which == WRITE_SCIENCES) {
			select = 1; // 2nd
		} else if (which == WRITE_SELF) {
			select = 2; // 3rd
		} else if (which == WRITE_SUGGEST) {
			select = 3; // 4th
		}
		complaint.setSelection(select); // 신고 내용에 맞게 세팅

		// image selection button
		Button selectImageBtn = (Button) findViewById(R.id.green_write_file_choose_btn);
		selectImageBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (absoluteFileList.size() > 2)
					Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_green_write_upload_limit),
							Toast.LENGTH_SHORT).show();
				else
					showDialog(PICTURE_SELECT_DIALOG);
			}
		});
		// write board button
		Button writeBtn = (Button) findViewById(R.id.green_write_submit_btn);
		writeBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// check contents
				if (checkParam() && NetworkManager.checkNetwork(GreencampusWriteActivity.this)) {
					showDialog(PROGRESS_DIALOG);
					writeBoard();
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ImageView selectedImageView = (ImageView) findViewById(R.id.green_write_selected_img_view);
		if (((BitmapDrawable) selectedImageView.getDrawable()) != null)
			((BitmapDrawable) selectedImageView.getDrawable()).getBitmap().recycle();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == RQ_PICTURE_SELECT) {
				// set imageView
				Uri imageUri = data.getData();
				/*
				 * 사진 촬영 선택, 갤럭시 노트 테스트 상황에서 Uri를 못 읽어옴 외장 메모리에 있는 컨텐츠의 최상위 row의
				 * 데이터를 읽어오는 방법으로 처리
				 */
				if (imageUri == null)
					imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				// add absoluteFileName
				String fileName = getFilenameFromUri(imageUri);
				absoluteFileList.add(fileName.trim());
				// set selectedImageview
				setSelectedImage(fileName);
				// get fileName
				fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
				// add fileName textView
				addFileNameTextView(fileName);
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case PROGRESS_DIALOG:
			Dialog progressDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			progressDialog.setContentView(R.layout.loading_progress);
			progressDialog.setCancelable(false);
			return progressDialog;
		case PICTURE_SELECT_DIALOG:
			AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
			alertBuilder.setTitle("사진 선택");
			alertBuilder.setCancelable(true);
			alertBuilder.setSingleChoiceItems(R.array.green_write_picture_select_list, -1, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Intent intent = null;
					switch (which) {
					case 0:
						intent = new Intent(Intent.ACTION_PICK);
						intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
						intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						break;
					case 1:
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						break;
					}
					if (intent != null){
//						intent.putExtra("crop", "true");
						startActivityForResult(intent, RQ_PICTURE_SELECT);
					}
					removeDialog(PICTURE_SELECT_DIALOG);
				}
			});
			return alertBuilder.create();
		default:
			return null;
		}
	}

	/**
	 * @param uri
	 * @return
	 */
	private String getFilenameFromUri(Uri uri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		String sortOrder = MediaStore.Images.Media._ID + " DESC";
		CursorLoader loader = new CursorLoader(getApplicationContext(), uri, proj, null, null, sortOrder);
		Cursor cursor = loader.loadInBackground();
		int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();

		return cursor.getString(index);
	}

	/**
	 * 
	 */
	private void writeBoard() {
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		// create httpManager
		HttpManager httpManager = new HttpManager();
		// init
		httpManager.init();
		// initSSL
		httpManager.InitSSL();
		try {
			/**************************
			 * upLoadImage
			 **************************/
			for (int index = 0; index < absoluteFileList.size(); index++) {
				// set httpPost
				httpManager.setHttpPost("https://www.mju.ac.kr/common/innoditorExecute.mbs?uploadpath=/upload/board/7088978/editor/");
				httpManager.initFilePost();
				// set file
				File file = new File(absoluteFileList.get(index));
				ContentBody cbFile = new FileBody(file, "image/jpeg");

				// set MultipartEntity
				MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));
				multipartContent.addPart("fileUpload", cbFile);
				String fileName = absoluteFileList.get(index).substring(absoluteFileList.get(index).lastIndexOf('/') + 1);
				multipartContent.addPart("orgFile", new StringBody(fileName));
				multipartContent.addPart("hdnUploadType", new StringBody("1"));
				httpManager.setEntity(multipartContent);
				// httpResponse
				HttpResponse fileResponse = null;
				// excute
				fileResponse = httpManager.executeHttpPost();
				// get Status
				StatusLine fileStatus = fileResponse.getStatusLine();
				if (fileStatus.getStatusCode() == HttpStatus.SC_OK) {
					HttpEntity entity = fileResponse.getEntity();
					// upload success
					if (entity != null) {
						// upLoadFileParsing
						parsingUploadImageFileName(entity);
					}
				} else {
					handler.sendEmptyMessage(UPLOAD_FAIL);
					break;
				}
			}
			/**************************
			 * write board
			 **************************/
			// set parameters
			HashMap<String, String> paramsMap = getBoardWriteParamMap();
			// set httpPost
			httpManager.setHttpPost(paramsMap, "https://www.mju.ac.kr/board/boardWriteExecute.mbs");
			// httpResponse
			HttpResponse boardResponse = null;
			// execute
			boardResponse = httpManager.executeHttpPost();
			// get response
			HttpEntity entity = boardResponse.getEntity();
			// upload success
			if (entity != null)
				handler.sendEmptyMessage(UPLOAD_SUCCESS);
			// upload fail
			else
				handler.sendEmptyMessage(UPLOAD_FAIL);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			handler.sendEmptyMessage(UPLOAD_FAIL);
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			handler.sendEmptyMessage(UPLOAD_FAIL);
			e.printStackTrace();
		} finally {
			httpManager.shutdown();
		}
	}

	/**
	 * @return
	 */
	private HashMap<String, String> getBoardWriteParamMap() {
		// get contents
		String subject = ((EditText) findViewById(R.id.green_write_subject_edittext)).getText().toString().trim();
		String id = ((EditText) findViewById(R.id.green_write_writer_id_edittext)).getText().toString().trim();
		String phone = ((EditText) findViewById(R.id.green_write_phone_edittext)).getText().toString().trim();
		if (phone == null)
			phone = "";
		String content = ((EditText) findViewById(R.id.green_write_content_edittext)).getText().toString();
		int complaintSelectedIndex = ((Spinner) findViewById(R.id.green_write_complaint_spinner)).getSelectedItemPosition() + 3;
		// set parameters
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("boardRecord.title", subject);
		paramsMap.put("boardRecord.userName", id);
		paramsMap.put("boardRecord.addContents", phone);
		paramsMap.put("boardRecord.contents", content + addImagePath);		
		paramsMap.put("boardRecord.mcategoryId", String.valueOf(complaintSelectedIndex));
		paramsMap.put("command", "write");
		paramsMap.put("boardSeq", "");
		paramsMap.put("boardRecord.boardConfig.boardId", "7088978");
		paramsMap.put("boardId", "7088978");
		paramsMap.put("boardRecord.boardSeq", "");
		paramsMap.put("boardRecord.refSeq", "0");
		paramsMap.put("boardRecord.famSeq", "0");
		paramsMap.put("boardRecord.pos", "0");
		paramsMap.put("boardRecord.depth", "0");
		paramsMap.put("boardRecord.readCnt", "0");
		paramsMap.put("regDate", "");
		paramsMap.put("boardRecord.emailReceive", "");
		paramsMap.put("boardRecord.basketYn", "");
		paramsMap.put("boardRecord.commentCnt", "0");
		paramsMap.put("boardRecord.fileCnt", "0");
		paramsMap.put("boardRecord.boardType", "07");
		paramsMap.put("boardRecord.remoteIp", "");
		paramsMap.put("filesize", "");
		paramsMap.put("pdsCnt", "20");
		paramsMap.put("pdsSize", "20971520");
		paramsMap.put("attechFile", "20971520");
		paramsMap.put("spage", "1");
		paramsMap.put("boardType", "07");
		paramsMap.put("listType", "07");
		paramsMap.put("boardRecord.userId", "");
		paramsMap.put("viewType", "");
		paramsMap.put("aliasYn", "Y");
		paramsMap.put("boardRecord.editorYn", "Y");
		paramsMap.put("upFile", "");
		paramsMap.put("upLoadFileValue", "");
		paramsMap.put("upLoadFileText", "");
		paramsMap.put("delFile", "");
		paramsMap.put("chkBoxSeq", "");
		paramsMap.put("imsiDir", "");
		paramsMap.put("boardRecord.boardConfig.boardName", "에너지낭비신고센터");
		paramsMap.put("mcategoryId", String.valueOf(complaintSelectedIndex));
		paramsMap.put("id", "mjukr_110500000000");
		paramsMap.put("boardRecord.frontYn", "Y");
		paramsMap.put("mcategory1", "");
		paramsMap.put("mcategory2", "");
		paramsMap.put("size_list", "");

		return paramsMap;
	}

	/**
	 * 
	 */
	private boolean checkParam() {
		// get subject
		String subject = ((EditText) findViewById(R.id.green_write_subject_edittext)).getText().toString();
		if (subject.equals("")) {
			Toast.makeText(getApplicationContext(), "제목을 입력하세요", Toast.LENGTH_SHORT).show();
			((EditText) findViewById(R.id.green_write_subject_edittext)).requestFocus();
			return false;
		}
		// get id
		String id = ((EditText) findViewById(R.id.green_write_writer_id_edittext)).getText().toString();
		if (id.equals("")) {
			Toast.makeText(getApplicationContext(), "학번 혹은 교번을 입력하세요", Toast.LENGTH_SHORT).show();
			((EditText) findViewById(R.id.green_write_writer_id_edittext)).requestFocus();
			return false;
		}
		// get content
		String content = ((EditText) findViewById(R.id.green_write_content_edittext)).getText().toString();
		if (content.equals("")) {
			Toast.makeText(getApplicationContext(), "내용을 입력하세요", Toast.LENGTH_SHORT).show();
			((EditText) findViewById(R.id.green_write_content_edittext)).requestFocus();
			return false;
		}
		return true;
	}

	/**
	 * @param entity
	 */
	private void parsingUploadImageFileName(HttpEntity entity) {
		// set SCRIPT element
		Vector<String> tagNames = new Vector<String>();
		tagNames.add(HTMLElementName.SCRIPT);

		// get SCRIPT element
		HttpManager httpManager = new HttpManager();

		HashMap<String, List<Element>> elementMap = httpManager.getHttpElementsMap(entity, tagNames);
		List<Element> elementsList = elementMap.get(HTMLElementName.SCRIPT);

		// element check
		if (elementsList != null) {
			for (Element element : elementsList) {
				// var check
				String temp = element.getContent().toString().trim();
				temp = temp.replaceAll("\r\n", "").replace("\r", "").replace("\n", "");

				// get upLoad image Path
				if (temp.contains("fnUploadResult")) {
					// calculate upload width, height
					int uploadWidth, uploadHeight;
					uploadWidth = (imgWidth > 400) ? 400 : imgWidth;
					uploadHeight = (imgWidth > 400) ? (int)((float)imgHeight *(float)((float)400 / (float)imgHeight)) : imgHeight;
					// set upload image path
					temp = temp.substring(temp.indexOf("'") + 1);
					addImagePath += "<br><img src=\"http://www.mju.ac.kr" + temp.substring(0, temp.indexOf("'")) + "\" alt=\"\" width=\""
							+ uploadWidth + "\" height=\"" + uploadHeight + "\"/><br/>";
				}
			}
		}
	}

	/**
	 * @param fileName
	 */
	private void addFileNameTextView(String fileName) {
		// get parent layout
		LinearLayout fileListLayout = (LinearLayout) findViewById(R.id.green_write_filelist_layout);
		// set textview
		TextView tv = new TextView(this);
		tv.setText(fileName);
		tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
		tv.setTextColor(getResources().getColor(android.R.color.black));
		tv.setPadding(5, 7, 0, 7);
		tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.green_write_filename_selector));
		// set layout
		LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f);
		tv.setLayoutParams(tvParams);
		// add view to parent
		fileListLayout.addView(tv, fileListLayout.getChildCount() - 1);
		// set onclick listener to delete
		tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final TextView tv = (TextView) v;
				new AlertDialog.Builder(GreencampusWriteActivity.this)
						.setTitle("사진 삭제")
						.setMessage(getResources().getString(R.string.msg_green_write_file_delete_content)).setCancelable(true)
						.setPositiveButton("확인", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								// get fileName from textView
								String fileNameFromTextView = tv.getText().toString();
								// get fileName from absoluteList and
								// remove
								for (int index = 0; index < absoluteFileList.size(); index++) {
									String tempFileName = absoluteFileList.get(index);
									tempFileName = tempFileName.substring(tempFileName.lastIndexOf('/') + 1);
									if (tempFileName.equals(fileNameFromTextView)) {
										absoluteFileList.remove(index);
										break;
									}
								}
								// if filelist is not empty
								// then fill new last file image
								if (absoluteFileList.size() > 0) {
									String lastFileName = absoluteFileList.get(absoluteFileList.size() - 1);
									setSelectedImage(lastFileName);
								}
								// if filelist empty imageview visibility GONE
								else {
									((ImageView) findViewById(R.id.green_write_selected_img_view)).setVisibility(ImageView.GONE);
									((TextView) findViewById(R.id.green_write_file_state_textview)).setVisibility(View.VISIBLE);
								}
								// remove textview from parent layout
								((LinearLayout) findViewById(R.id.green_write_filelist_layout)).removeView(tv);
							}
						}).setNegativeButton("취소", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								// do nothing
							}
						}).show();
			}
		});
	}

	/**
	 * @param imageUri
	 */
	private void setSelectedImage(String pathName) {
		// file
		File imageFile = new File(pathName);
		long fileSize = imageFile.length();
		// set bitmap option
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inDensity = DisplayMetrics.DENSITY_HIGH;
		opt.inTargetDensity = getResources().getDisplayMetrics().densityDpi;
		opt.inSampleSize = (int) (fileSize / 400000);
		// decode image
		Bitmap bitmap = BitmapFactory.decodeFile(pathName, opt);
		BitmapDrawable bmDrawable = new BitmapDrawable(bitmap);
		//set width, height variables
		imgWidth = bitmap.getWidth();
		imgHeight = bitmap.getHeight();
		// set imageView
		ImageView selectedImgView = (ImageView) findViewById(R.id.green_write_selected_img_view);
		selectedImgView.setImageDrawable(bmDrawable);
		selectedImgView.setScaleType(ScaleType.CENTER_CROP);
		// set filename to selectedImgView by tag
		String fileName = absoluteFileList.get(absoluteFileList.size() - 1).toString();
		fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
		selectedImgView.setTag(fileName);
		// set visibility
		selectedImgView.setVisibility(View.VISIBLE);
		((TextView) findViewById(R.id.green_write_file_state_textview)).setVisibility(View.GONE);
	}
}
/* end of file */